import { GOOGLE_MAP_KEY } from '@/config/config';
import { t } from 'i18next';
import { PermissionsAndroid, Platform } from 'react-native';
import {
  init,
  Geolocation as AMapLocation,
  setLocatingWithReGeocode,
  setNeedAddress,
  type Location,
  type ReGeocode,
  type Coordinates,
} from 'react-native-amap-geolocation';
import toast from './toast';
import PermissionUtils, { Permission, PERMISSIONS, PermissionStatus } from './PermissionUtils';
class Geolocation extends AMapLocation {
  static async requestPermissions() {
    let permissions: Permission[] = [];
    if (Platform.OS === 'android') {
      permissions.push(
      PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
      PERMISSIONS.ANDROID.ACCESS_COARSE_LOCATION,
      )
    } else {
      permissions.push(PERMISSIONS.IOS.LOCATION_WHEN_IN_USE)
    }
    const status = await PermissionUtils.checkMultiplePermissions(permissions);
    return status;
  }

  /**
   * 地理位置模块初始化构造函数
   * 在 Android 设备上请求访问地理位置的权限
   * 如果用户拒绝授权，则会弹出一个提示框，提示用户需要启用权限才能使用该功能
   * 根据平台（iOS 或 Android）初始化地理位置模块，并设置相应的配置选项
   */
  constructor() {
    (async () => {
      // const permission =
      //   Platform.OS === 'android'
      //     ? PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION
      //     : PERMISSIONS.IOS.LOCATION_WHEN_IN_USE;
      // const status = await PermissionUtils.checkPermission(permission);
      // if (!status.granted) {
      //   toast.showToast({
      //     message: t('staticRoutes.noPower'),
      //   });
      // }
      // 初始化地理位置模块
      await init({
        ios: '24f5d1a32ef9308b89ee7ba234c2d9a6',
        android: 'eab930899478d9be0431dc790945eaa6',
      });
      // 根据平台设置地理位置模块的配置选项
      Platform.OS === 'ios' && setLocatingWithReGeocode(true);
      Platform.OS === 'android' && setNeedAddress(true);
    })();
    super();
  }
  /**
   * Gets the current position with the country.
   *
   * @returns A promise which resolves to an object containing the country and other location information.
   * If the country is not provided by the device, it will use the Google Maps Geocoding API to get the country.
   * The country will be set to `'China'` if it is `' '`.
   *
   * Note: This method will use the Google Maps Geocoding API if the country is not provided by the device.
   * The Google Maps Geocoding API will return the country in English.
   * The country will be set to `'China'` if it is `' '`.
   */
  async getCurrentPosition() {
    return new Promise<Partial<Location & ReGeocode>>((resolve, reject) => {
      const timer = setTimeout(() => {
        reject(new Error('timeout'));
      }, 1000 * 10);
      Geolocation.getCurrentPosition(
        async ({
          coords,
          location,
        }: {
          location: Location & ReGeocode;
          coords: Coordinates;
        }) => {
          if (!location.country) {
            // If the country is not provided by the device, use the Google Maps Geocoding API to get the country.
            try {
              const data = await fetch(
                `https://maps.googleapis.com/maps/api/geocode/json?latlng=${coords.latitude},${coords.longitude}&key=${GOOGLE_MAP_KEY}&language=en`,
                {
                  method: 'get',
                }
              ).then((res) => {
                return res.json();
              });
              const country = data.results.find((item) => {
                // Find the country in the results.
                return item.types.includes('country');
              });
              // Resolve with the country.
              resolve({
                country: country?.formatted_address || '',
              });
            } catch (e) {
              reject(e);
            }
          } else {
            // Resolve with the location information.
            resolve({
              country: location.country === '中国' ? 'China' : location.country,
            });
          }
          clearTimeout(timer);
        },
        (e) => {
          clearTimeout(timer);
          // Reject with the error.
          reject(e);
        }
      );
    });
  }
}

export default Geolocation;
